package com.km.wskj.itmonitor.pager.monitor.database;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.DataBase;
import com.km.wskj.itmonitor.model.DBItem;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.database.domain.DbMsg;
import com.km.wskj.itmonitor.pager.monitor.database.mysql.MySQLDetailActivity;
import com.km.wskj.itmonitor.pager.monitor.database.oracle.OracleDetailActivity;
import com.km.wskj.itmonitor.pager.monitor.database.sqlserver.SQLServerDetailActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.km.wskj.itmonitor.utils.TimeUtils;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;


public class DBListActivity extends LActivity {
    private static final String TAG = "DBListActivity";

    //ui
    @BindView(R.id.db_spinner)
    Spinner mSpinner;
    @BindView(R.id.db_zrcListView)
    ZrcListView mZrcListView;

    //data

    private List<DataBase> dataBaseList;
    private int lastUpdateNum;
    private MyAdapter mAdapter;
    private int pageIndex;
    private String databaseType;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datebase);
        ButterKnife.bind(this);
        //沉浸式
        StatusBarCompat.compat(context, getResources().getColor(R.color.colorWs_blue));
        initSpinner();

    }

    private void initData() {
        pdc.databaseList(HTTP_TASK_TAG, 0, Constant.PageListSize, databaseType, new ZxlGenericsCallback<List<DataBase>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<DataBase> dbs, int i) {
                dataBaseList = dbs;
                lastUpdateNum = dbs.size();
                pageIndex = 0;

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
        initPullToRefresh();
    }

    private void initSpinner() {
        pdc.databaseType(HTTP_TASK_TAG, new ZxlGenericsCallback<List<DBItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<DBItem> dbi, int i) {
                DBItem dbItem = new DBItem();
                dbItem.codeName = "全部";
                dbItem.id = "";
                List<DBItem> mDatas = new ArrayList<DBItem>();
                mDatas.add(dbItem);
                mDatas.addAll(dbi);

                //适配器
                ArrayAdapter<DBItem> arr_adapter = new ArrayAdapter<DBItem>(context,
                        android.R.layout.simple_spinner_item, mDatas);
                //设置样式
                arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                //加载适配器
                mSpinner.setAdapter(arr_adapter);

                //事件监听
                mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                        DBItem dbi = (DBItem) adapterView.getItemAtPosition(i);
                        /**
                         * 设置spinner字体样式
                         */
                        TextView tv = (TextView) view;
                        tv.setTextColor(getResources().getColor(R.color.white));    //设置颜色
                        tv.setTextSize(16.0f);    //设置大小
                        tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);   //设置居中
                        databaseType = dbi.id;
                        initData();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });
            }
        });

    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                DataBase dataBase = (DataBase) parent.getItemAtPosition(position);
                //不同数据库，跳转不同页面
                if (dataBase.codeName.equals("MySql"))
                    intent = new Intent(context, MySQLDetailActivity.class);
                if (dataBase.codeName.equals("SQLServer"))
                    intent = new Intent(context, SQLServerDetailActivity.class);
                if (dataBase.codeName.equals("Oracle"))
                    intent = new Intent(context, OracleDetailActivity.class);

                intent.putExtra("id", dataBase.id);
                intent.putExtra("ip", dataBase.ip);
                intent.putExtra("data", dataBase);

                startActivity(intent);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    private void onRefresh() {
        pdc.databaseList(HTTP_TASK_TAG, 0, Constant.PageListSize, databaseType, new ZxlGenericsCallback<List<DataBase>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败！");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<DataBase> dbs, int i) {
                dataBaseList = dbs;
                lastUpdateNum = dbs.size();
                pageIndex = 0;

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });
    }

    private void onLoadMore() {
        pdc.databaseList(HTTP_TASK_TAG, pageIndex + 1, Constant.PageListSize, databaseType, new ZxlGenericsCallback<List<DataBase>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<DataBase> dbs, int i) {

                lastUpdateNum = dbs.size();
                if (dbs.size() > 0) {
                    dataBaseList.addAll(dbs);
                    pageIndex++;
                }

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });

    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (dataBaseList == null) {
                return 0;
            }
            return dataBaseList.size();
        }

        @Override
        public Object getItem(int position) {
            DataBase item = dataBaseList.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_monitor_list);
            DataBase item = dataBaseList.get(position);
            helper.setText(R.id.tv_item_name, item.name);
            helper.setText(R.id.tv_item_ip, item.ip);

            //计算运行时间
            pdc.db_startup(HTTP_TASK_TAG, item.id, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int i) {
                    LogUtils.e(TAG, e);
                }

                @Override
                public void onResponse(String str, int i) {
                    DbMsg dbMsg = JSON.parseObject(str, DbMsg.class);
                    String distanceTime = TimeUtils.getDistanceTime(dbMsg.DATA, TimeUtils.DateToString(new Date()));
                    helper.setText(R.id.tv_item_runTime, distanceTime);
                }
            });
            //运行状态 1正常 2故障
            switch (item.status) {
                case 1:
                    helper.setImageResource(R.id.iv_item_state, R.drawable.data_s_g);
                    break;
                case 2:
                    helper.setImageResource(R.id.iv_item_state, R.drawable.data_s_r);
                    break;
            }
            return helper.getView();
        }

    }


    //点击事件
    @OnClick({R.id.db_statistics, R.id.db_back})
    public void onClick(View view) {
        switch (view.getId()) {
            //统计
            case R.id.db_statistics:
                openIntent(DBStatisticsActivity.class, true);
                break;
            //返回
            case R.id.db_back:
                finish();
                break;
        }
    }
}
